package vip.idiy.anwei_android_iot;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import vip.idiy.anwei_android_iot.adapters.RecyclerItemClickListener;
import vip.idiy.anwei_android_iot.adapters.RecyclerViewSwitchAdapter;
import vip.idiy.anwei_android_iot.dialog.IconSelectDialog;
import vip.idiy.anwei_android_iot.domin.DeviceInfo;
import vip.idiy.anwei_android_iot.domin.DeviceMode;
import vip.idiy.anwei_android_iot.domin.DeviceScene;
import vip.idiy.anwei_android_iot.domin.DeviceType;
import vip.idiy.anwei_android_iot.domin.IconEntity;
import vip.idiy.anwei_android_iot.domin.mqtt.SubData;
import vip.idiy.anwei_android_iot.domin.mqtt.SwitchTypeData;
import vip.idiy.anwei_android_iot.domin.mqtt.sendParam.SwitchSendParam;
import vip.idiy.anwei_android_iot.utils.DatabaseUtil;
import vip.idiy.anwei_android_iot.utils.EditTextDialog;
import vip.idiy.anwei_android_iot.utils.IotUtil;
import vip.idiy.anwei_android_iot.utils.MQTTUtil;
import vip.idiy.anwei_android_iot.utils.SpUtils;
import vip.idiy.anwei_android_iot.utils.ViewUtil;
import vip.idiy.anwei_android_iot.utils.dbHandle.DeviceInfoHandle;
import vip.idiy.anwei_android_iot.utils.dbHandle.SceneDataHandle;
import vip.idiy.anwei_android_iot.utils.dbHandle.TypeDataHandle;
import vip.idiy.anwei_android_iot.views.LayoutBasicInfo;

/**
 * 设备操作处理
 */
public class DeviceSettingHandleActivity extends AppCompatActivity {
    private final String TAG = "myTag " + " DeviceSettingHandleActivity ";
    private BroadcastReceiver receiver;
    private DeviceInfoHandle deviceInfoHandle;
    private SceneDataHandle sceneDataHandle;
    private TypeDataHandle typeDataHandle;
    private DeviceInfo deviceInfo;
    private LayoutBasicInfo basicInfo_title_device_id;
    private LayoutBasicInfo basicInfo_title_device_wifi;
    private LayoutBasicInfo basicInfo_title_device_type;
    private LayoutBasicInfo basicInfo_title_device_scene;
    private LayoutBasicInfo basicInfo_title_device_firmware;

    private LayoutInflater inflater;
    private SubData subData;

    private final String TYPE_SWITCH = "switch";
    private List<SwitchTypeData> switchList;


    private RecyclerView layout_switch_handle_recycler_view;
    private MQTTUtil mqttUtil;
    private final String MQTT_PUB_DEVICE = "anwei_iot_device_pub/";
    private RecyclerViewSwitchAdapter recyclerViewSwitchAdapter;
    private MediaPlayer mediaPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_setting_handle);
        // 设置设透明状态栏,导航栏. 状态栏字体修改为黑色
        ViewUtil.setViewStyle(this, true);

        switchList = new ArrayList<>();


        initData();

        initView();

        // 获取MQTT信息
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 在这里处理消息
                String topic = intent.getStringExtra("topic");
                String[] topicSplit = topic.split("/");
                if (topicSplit.length == 2) {
                    String message = intent.getStringExtra("message");
                    subData = IotUtil.analysisResult(message, SubData.class);
                    if (subData.getDeviceId().equals(deviceInfo.getDeviceId()) && TYPE_SWITCH.equals(subData.getType())) {
                        switchDataHandle(message);
                    }
                }
                if (topicSplit.length == 6) {
                    // 离线
                    if(topicSplit[5].equals("disconnected")){
                        basicInfo_title_device_wifi.setCentreImg(IotUtil.checkRssi(-101));
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter("MQTT_MESSAGE_ARRIVED");
        registerReceiver(receiver, filter);

        mediaPlayer = MediaPlayer.create(this, R.raw.switching_sound);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 获取MainActivity发来的设备ID
        Intent intent = getIntent();
        String deviceId = intent.getStringExtra("deviceId");
        // 根据设备获取数据库设备信息
        DatabaseUtil databaseUtil = DatabaseUtil.getInstance(this);
        deviceInfoHandle = new DeviceInfoHandle(databaseUtil);
        sceneDataHandle = new SceneDataHandle(databaseUtil);
        typeDataHandle = new TypeDataHandle(databaseUtil);
        deviceInfo = deviceInfoHandle.selectByDeviceId(deviceId);
        subData = IotUtil.analysisResult(deviceInfo.getDeviceData(), SubData.class);
        mqttUtil = MQTTUtil.getInstance();
    }

    /**
     * 处理MQTT消息(开关)
     *
     * @param data
     */
    private void switchDataHandle(String data) {
        List<SwitchTypeData> switchLists = IotUtil.analysisList(data, "switchList", SwitchTypeData.class);
        if (recyclerViewSwitchAdapter != null) {
            for (int i = 0; i < switchLists.size(); i++) {
                switchList.get(i).setStatus(switchLists.get(i).isStatus());
                switchList.get(i).setSwitchName(switchLists.get(i).getSwitchName());
                recyclerViewSwitchAdapter.notifyItemChanged(i);
            }
        }
        basicInfo_title_device_wifi.setCentreImg(IotUtil.checkRssi(subData.getRssi()));
        basicInfo_title_device_firmware.setCentreContent(subData.getFirmwareVersion());
    }

    /**
     * 初始化窗口
     */
    private void initView() {
        TextView layout_reuse_head_tv_title = findViewById(R.id.layout_reuse_head_tv_title);
        layout_reuse_head_tv_title.setText(R.string.table_device_handle);
        // 返回按钮
        findViewById(R.id.layout_reuse_head_return_myImageButton).setOnClickListener(v -> finish());

        LinearLayout device_setting_details_linear_layout = findViewById(R.id.device_setting_details_linear_layout);

        // 设备号码
        basicInfo_title_device_id = new LayoutBasicInfo(this).init(false, true, false, false, false, false)
                .setLeftText(getString(R.string.title_device_id))
                .setCentreContent(deviceInfo.getDeviceId())
                .setLineBackground(R.drawable.ripple_gray);
        // 网络状态
        basicInfo_title_device_wifi = new LayoutBasicInfo(this).init(false, false, true, false, false, false)
                .setLeftText(getString(R.string.title_device_wifi))
                .setCentreImg(IotUtil.checkRssi(deviceInfo.getRssi()))
                .setLineBackground(R.drawable.ripple_gray);
        // 设备型号
        basicInfo_title_device_type = new LayoutBasicInfo(this).init(false, true, false, false, false, true)
                .setLeftText(getString(R.string.title_device_type))
                .setCentreContent(deviceInfo.getTypeName())
                .setRightImg(R.mipmap.icon_right)
                .setLineBackground(R.drawable.ripple_gray)
                .setLineClick(v -> {
                    // 读入类型数据,转成枚举类
                    List<DeviceType> list = typeDataHandle.getList(null, null);
                    ArrayList<IconEntity> iconLit = new ArrayList<>();
                    for (DeviceType t : list) {
                        IconEntity iconEntity = new IconEntity(t.getTypeName(), IotUtil.checkImg(t.getTypeImg()).getIcon(), t.getTypeId());
                        iconLit.add(iconEntity);
                    }
                    IconSelectDialog dialog = IconSelectDialog.newInstance(
                            DeviceSettingHandleActivity.this,
                            getString(R.string.please_select_type),
                            entity -> {
                                basicInfo_title_device_type.setCentreContent(entity.getIconName());
                                deviceInfo.setTypeId(entity.getQueryId());
                                updateDeviceInfo();

                            }, iconLit);
                    dialog.show();
                });
        // 设备位置
        basicInfo_title_device_scene = new LayoutBasicInfo(this).init(false, true, false, false, false, true)
                .setLeftText(getString(R.string.title_device_scene))
                .setCentreContent(deviceInfo.getSceneName())
                .setRightImg(R.mipmap.icon_right)
                .setLineBackground(R.drawable.ripple_gray)
                .setLineClick(v -> {
                    List<DeviceScene> list = sceneDataHandle.getList(null, null);
                    ArrayList<IconEntity> iconLit = new ArrayList<>();
                    for (DeviceScene s : list) {
                        IconEntity iconEntity = new IconEntity(s.getSceneName(), IotUtil.checkIcon(s.getSceneIcon()).getIcon(), s.getSceneId());
                        iconLit.add(iconEntity);
                    }
                    IconSelectDialog dialog = IconSelectDialog.newInstance(
                            DeviceSettingHandleActivity.this,
                            getString(R.string.please_select_scene),
                            entity -> {
                                basicInfo_title_device_scene.setCentreContent(entity.getIconName());
                                deviceInfo.setSceneId(entity.getQueryId());
                                updateDeviceInfo();
                            },
                            iconLit);
                    dialog.show();
                });
        // 开关程序版本
        basicInfo_title_device_firmware = new LayoutBasicInfo(this).init(false, true, false, false, false, true)
                .setLeftText(getString(R.string.title_device_firmware))
                .setCentreContent(deviceInfo.getFirmwareVersion())
                .setRightImg(R.mipmap.icon_right)
                .setLineBackground(R.drawable.ripple_gray)
                .setLineClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 更新

                    }
                });

        device_setting_details_linear_layout.addView(basicInfo_title_device_id);
        device_setting_details_linear_layout.addView(basicInfo_title_device_wifi);
        device_setting_details_linear_layout.addView(basicInfo_title_device_type);
        device_setting_details_linear_layout.addView(basicInfo_title_device_scene);
        device_setting_details_linear_layout.addView(basicInfo_title_device_firmware);

        inflater = LayoutInflater.from(this);

        LinearLayout device_setting_function_linear_layout = findViewById(R.id.device_setting_function_linear_layout);
        // 如果是开关类型  根据类型添加页面
        if (TYPE_SWITCH.equals(subData.getType())) {
            View layout_switch_handle = inflater.inflate(R.layout.layout_switch_handle, null);
            layout_switch_handle_recycler_view = layout_switch_handle.findViewById(R.id.layout_switch_handle_recycler_view);

            ((SimpleItemAnimator) Objects.requireNonNull(layout_switch_handle_recycler_view.getItemAnimator())).setSupportsChangeAnimations(false);
            // layout_switch_handle_recycler_view.addItemDecoration(new SpaceItemDecoration(10));

            layout_switch_handle_recycler_view.addOnItemTouchListener(
                    new RecyclerItemClickListener(this,
                            layout_switch_handle_recycler_view,
                            new RecyclerItemClickListener.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    // 单击
                                    SwitchTypeData switchTypeData = switchList.get(position);
                                    switchTypeData.setStatus(!switchTypeData.isStatus());
                                    // 发送开关
                                    sendSwitchHandle(DeviceMode.MODE_OPERATION);
                                    mediaPlayer.start();
                                }

                                @Override
                                public void onItemLongClick(View view, int position) {
                                    // 长按
                                    EditTextDialog editTextDialog = new EditTextDialog(
                                            DeviceSettingHandleActivity.this,
                                            getString(R.string.dialog_title_update_device_switch_name, switchList.get(position).getSwitchName()));
                                    editTextDialog.setOnTextEnteredListener(text -> {
                                        SwitchTypeData switchTypeData = switchList.get(position);
                                        switchTypeData.setSwitchName(text.trim());
                                        sendSwitchHandle(DeviceMode.MODE_UPDATE_SWITCH_NAME);
                                    });
                                    editTextDialog.show();
                                }
                            }));

            device_setting_function_linear_layout.addView(layout_switch_handle);
            switchList = IotUtil.analysisList(deviceInfo.getDeviceData(), "switchList", SwitchTypeData.class);
            layout_switch_handle_recycler_view.setAdapter(null);
            recyclerViewSwitchAdapter = new RecyclerViewSwitchAdapter(switchList);
            // 每行显示
            StaggeredGridLayoutManager layoutManager =
                    new StaggeredGridLayoutManager(7, StaggeredGridLayoutManager.VERTICAL);
            layout_switch_handle_recycler_view.setLayoutManager(layoutManager);
            layout_switch_handle_recycler_view.setAdapter(recyclerViewSwitchAdapter);
        }
    }

    /**
     * 更新数据
     */
    private void updateDeviceInfo() {
        deviceInfo.setDeviceData(null);
        deviceInfoHandle.update(deviceInfo);
    }

    /**
     * 发送开关参数
     */
    private void sendSwitchHandle(int mode) {
        SwitchSendParam switchSendParam = new SwitchSendParam();
        switchSendParam.setDeviceId(deviceInfo.getDeviceId());
        switchSendParam.setType(subData.getType());

        switchSendParam.setMode(mode);
        // switchSendParam.setUrl();
        switchSendParam.setSwitchList(switchList);
        Object o = JSONObject.toJSON(switchSendParam);
        mqttUtil.publishMQTT(MQTT_PUB_DEVICE + deviceInfo.getDeviceId(), o.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        mediaPlayer.stop();
        mediaPlayer.release();
    }
}